import Food from './food'
import Snake from './snake'
import ScorePanel from './scorePanel'

export default class GameController {
    food: Food;
    snake: Snake;
    scorePanel: ScorePanel;
    // 按键的方向（蛇移动的方向）
    direction: string = '';
    // 游戏是否结束
    isLive = true;

    constructor() {
        this.food = new Food()
        this.snake = new Snake()
        this.scorePanel = new ScorePanel()
        // 创建对象后即游戏开始
        this.init()
    }

    init() {
        console.log('游戏开始')
        // 绑定键盘事件
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        this.run()
    }

    /**
     * ArrowUp Up
     * ArrowDown Down
     * ArrowLeft Left
     * ArrowRight Right
     * 上面是键盘按上下左右后返回的event.key
     * 由于IE浏览器不合群，所以事件名称和其他浏览器有区别
     * 
    */
    keydownHandler(event: KeyboardEvent) {
        // 根据event.key来判断上下左右
        this.direction = event.key;
    }

    run() {
        // 获取蛇现在的坐标
        let X = this.snake.X;
        let Y = this.snake.Y;

        switch (this.direction) {
            case 'ArrowUp':
            case 'Up':
                Y -= 10;
                break;
            case 'ArrowDown':
            case 'Down':
                Y += 10;
                break;
            case 'ArrowLeft':
            case 'Left':
                X -= 10;
                break;
            case 'ArrowRight':
            case 'Right':
                X += 10;
                break;
            default:
        }

        // 检查蛇是否吃到了食物
        this.checkEat(X, Y)

        try {
            this.snake.X = X;
            this.snake.Y = Y;
        } catch (e) {
            alert(e.message+ 'Game Over！')
            this.isLive = false
        }


        // 开启一个定时器
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
    }

    checkEat(x:number, y:number) {
        if (x === this.food.X && y === this.food.Y) {
            this.snake.addBodies()
            this.food.change()
            this.scorePanel.addScore()
        }
    }

}